package com.googlecode.afdbaccess.config.webconfig;

import org.apache.log4j.Logger;

import com.googlecode.afdbaccess.cache.DbCache;
import com.googlecode.afdbaccess.cache.connectionpool.interfaces.ConnectionPool;
import com.googlecode.afdbaccess.cache.connectionpool.interfaces.ConnectionPoolFactory;
import com.googlecode.afdbaccess.cache.exceptions.DataLayerException;


public class DbInitExceptionHolder {
    private final static Logger log = Logger.getLogger(DbInitExceptionHolder.class);  

    private DbCache dbCache;
    private DataLayerException initException;

    /**
     * Creates the cache, and stores any init exception. Meant to be wrapped by a singleton.
     * @return
     */
    public DbInitExceptionHolder(String root) {
        try {
            // find out which pool to use
            ConnectionPoolFactory connectionPoolFactory = ReadConfiguration.instanciatePoolFactory();
            ConnectionPool connectionPool = connectionPoolFactory.getNewConnectionPool(root);

            dbCache = new DbCache(connectionPool);
        } catch(Throwable throwable) {
            log.fatal("Exception was thrown when initiating DbPool!", throwable);
            initException = new DataLayerException("Exception was thrown when initiating DbPool!", throwable);
        } finally {
            log.debug("DbCache initializing completed.");
        }
    }

    public DbCache getDbCache() throws DataLayerException {
        if(initException == null) {
            return dbCache;
        } else {
            throw initException;
        }
    }

    public void close() throws DataLayerException {
        getDbCache().close();
    }
}
